
var Datatable = function () {

    var tableOptions;
    var dataTable;
    var table;
    var tableContainer;
    var tableWrapper;
    var tableInitialized = false;
    var ajaxParams = {};
    var the;
    var checkbox = 'tbody > tr > td input[type="checkbox"]';
    var optTable;
	var searchData = {};
    
    //固定列
    var fixedColumns = function() {
		if (tableOptions.fixedColumns == 0) return;
    	$(".fixed-columns-wrapper").remove();
		var $table = $("<table></table>");
		var $thead = $("<thead></thead>");
		var $tbody = $("<tbody></tbody>");
		var rowLength = $("tr", table).length;
		$table.attr("id", "fixedTable");
		$table.attr("class", table.attr("class"));
		$table.attr("style", table.attr("style"));
		for (var i=0; i<rowLength; i++) {
			var $tr = $("<tr></tr>");
			var tr = $("tr", table).eq(i);
			$tr.attr("class", tr.attr("class"));
			$tr.attr("style", tr.attr("style"));
			for (var j=0; j<tableOptions.fixedColumns; j++) {
				var td = tr.children().eq(j);
				var $td = td.clone();
				$tr.append($td);
				$td.children(".checker").removeClass("checker");
				var rowspan = parseInt(td.attr("rowspan")) - 1;
				if (rowspan > 0) {
					$td.attr("rowspan", 1);
					$td.css("padding-top", (21*rowspan)+"px");
					$td.css("padding-bottom", (20*rowspan)+"px");
					if (j == 0) {
						i += rowspan;
					}
				}
			}
			if (tr.parent().is("thead")) {
				$thead.append($tr);
			} else {
				$tbody.append($tr);
			}
		}
		$table.append($thead);
		$table.append($tbody);
		var $wrapper = $("<div class='fixed-columns-wrapper'></div>");
		$wrapper.append($table);
		$(".table-scrollable").prepend($wrapper);
	}
    
    //绑定表头复选框事件
    var bindCheckboxGroupChange = function() {
    	var c = $('.group-checkable', $(optTable));
    	if (c.size() === 1) {
            c.attr("checked", false);
            $.uniform.update(c);
            c.change(function () {
                var set = $(checkbox, $(optTable));
                var checked = $(this).is(":checked");
                $(set).each(function () {
                    $(this).attr("checked", checked);
                });
                $.uniform.update(set);
                countSelectedRecords();
            });
        }
    }
    //绑定复选框事件
    var bindCheckboxChange = function() {
    	$(checkbox, optTable).unbind().bind('change', function () {
            countSelectedRecords();
        });
    }
    //绑定查询按钮单击事件
    var bindSubmitClick = function() {
		$('.filter-submit', optTable).unbind().bind('click', function (e) {
            e.preventDefault();
            submitFilter();
        });
    }
    //绑定重置按钮单击事件
    var bindCancelClick = function() {
    	$('.filter-cancel', optTable).unbind().bind('click', function (e) {
            e.preventDefault();
            resetFilter();
        });
    }
	//应用查询，设置查询参数
	var applyFilter = function(remember) {
		$('textarea.form-filter, select.form-filter, input.form-filter:not([type="radio"],[type="checkbox"])', table).each(function () {
			if (remember) searchData[$(this).attr("name")] = $(this).val();
            the.setAjaxParam($(this).attr("name"), $(this).val());
        });
        $('input.form-filter[type="checkbox"]:checked', table).each(function () {
			if (remember) searchData[$(this).attr("name")] = $(this).val();
            the.addAjaxParam($(this).attr("name"), $(this).val());
        });
        $('input.form-filter[type="radio"]:checked', table).each(function () {
			if (remember) searchData[$(this).attr("name")] = $(this).val();
            the.setAjaxParam($(this).attr("name"), $(this).val());
        });	
	}
    //查询
    var submitFilter = function () {
        the.setAjaxParam("action", tableOptions.filterApplyAction);
        applyFilter(false);
        dataTable.ajax.reload();
    }
    //重置
    var resetFilter = function () {
        $('textarea.form-filter, select.form-filter, input[type="text"].form-filter', table).each(function () {
			$(this).val(searchData[$(this).attr("name")] || "");
        });
        $('input.form-filter[type="checkbox"]', table).each(function () {
            $(this).attr("checked", searchData[$(this).attr("name")] || false);
        });
        the.clearAjaxParams();
        the.addAjaxParam("action", tableOptions.filterCancelAction);
		applyFilter(false);
        dataTable.ajax.reload();
    }
    //合计选择的记录数
    var countSelectedRecords = function () {
        var selected = $(checkbox + ':checked', optTable).size();
        var text = tableOptions.dataTable.language.metronicGroupActions;
        if (selected > 0) {
            $('.table-group-actions', tableWrapper).text(text.replace("_TOTAL_", selected));
        } else {
            $('.table-group-actions', tableWrapper).text("");
        }
    }

    return {

        init: function (options) {

            if (!$().dataTable) {
                return;
            }

            the = this;

            options = $.extend(true, {
                src: "", 
                filterApplyAction: "filter",
                filterCancelAction: "filter_cancel",
                resetGroupActionInputOnSuccess: true,
                fixedContainer: $("#table-scrollable"),
    			fixedColumns: 0,
                loadingMessage: message['datatable.loading.message'],
                dataTable: {
                    "dom": "<'row'<'col-md-8 col-sm-12'pli><'col-md-4 col-sm-12'<'table-group-actions pull-right'>>r><'table-scrollable't><'row'<'col-md-8 col-sm-12'pli><'col-md-4 col-sm-12'>>", 
                    "pageLength": 10,
					"lengthMenu": [5, 10, 15, 20, 25, 30, 50, 100, 200, 300, 500, 1000],
                    "language": {
                        "metronicGroupActions": message['datatable.selected.total'],
                        "metronicAjaxRequestGeneralError": message['datatable.ajax.request.error'],
                        "lengthMenu": "<span class='seperator'>|</span>" + message['datatable.pagination.size'],
                        "info": "<span class='seperator'>|</span>" + message['datatable.records.total'],
                        "infoEmpty": message['datatable.records.empty'],
                        "emptyTable": message['datatable.records.empty'],
                        "zeroRecords": message['datatable.records.empty'],
                        "paginate": {
                            "previous": message['datatable.pagination.previous'],
                            "next": message['datatable.pagination.next'],
                            "last": message['datatable.pagination.last'],
                            "first": message['datatable.pagination.first'],
                            "page": message['datatable.pagination.page'],
                            "pageOf": message['datatable.pagination.pageof']
                        }
                    },

                    "orderCellsTop": true,
                    "columnDefs": [{
                        'orderable': false,
                        'targets': [0]
                    }],

                    "pagingType": "bootstrap_extended", // pagination type(bootstrap, bootstrap_full_number or bootstrap_extended)
                    "autoWidth": false, // disable fixed width and enable fluid table
                    "processing": false, // enable/disable display message box on record load
                    "serverSide": true, // enable/disable server side ajax loading
                    "ajax": {
                        "url": "",
                        "type": "POST",
                        "timeout": 20000,
                        "data": function (data) {
							// 分页
                        	var d = {
                        		page : data["start"] / data["length"],
                        		size : data["length"]
                        	}
                        	$.extend(data, d);
							// 排序
							var sort = '';
							$.each(data.order, function(i, val) {
								sort += data.columns[val.column].data + ',' + val.dir + ';';
							});
							data.sort = sort;
                        	// 去掉不需要的参数
                        	for (var name in data) {
                        		if (name.search(/draw|columns|search|start|length|order/) != -1) {
                        			delete data[name];
                        		}
                        	}
                        	
                            $.each(ajaxParams, function (key, value) {
                                data[key] = value;
                            });
							
                            Metronic.blockUI({
                                message: tableOptions.loadingMessage,
                                target: tableContainer, 
                                overlayColor: 'none', 
                                cenrerY: true, 
                                boxed: true
                            });
                        },
                        "dataSrc": function (res) { 
							if (res.errors) {
								Metronic.alert({
									type: 'danger',
									icon: 'warning',
									message: res.errors[0].message,
									container: tableWrapper,
									place: 'prepend'
								});
							    Metronic.unblockUI(tableContainer);
								return;	
							}
							
                            if (res.customActionMessage) {
                                Metronic.alert({
                                    type: (res.customActionStatus == 'OK' ? 'success' : 'danger'),
                                    icon: (res.customActionStatus == 'OK' ? 'check' : 'warning'),
                                    message: res.customActionMessage,
                                    container: tableWrapper,
                                    place: 'prepend'
                                });
                            }

                            if (res.customActionStatus) {
                                if (tableOptions.resetGroupActionInputOnSuccess) {
                                    $('.table-group-action-input', tableWrapper).val("");
                                }
                            }

                            Metronic.unblockUI(tableContainer);
                            
                            $("[id^='aggregate_']").each(function() {
                            	$(this).html(res[$(this).attr("id").split("_")[1]]);
                            });
							
							if (tableOptions.onSuccess) {
                                tableOptions.onSuccess.call(undefined, res);
                            }

                            return res.data;
                        },
                        "error": function (res) {
                            if (tableOptions.onError) {
                                tableOptions.onError.call(undefined, res);
                            }

                            Metronic.alert({
                                type: 'danger',
                                icon: 'warning',
                                message: tableOptions.dataTable.language.metronicAjaxRequestGeneralError,
                                container: tableWrapper,
                                place: 'prepend'
                            });

                           Metronic.unblockUI(tableContainer);
                        }
                    },

                    "drawCallback": function (oSettings) { // run some code on table redraw
                        if (tableInitialized === false) { // check if table has been initialized
                            tableInitialized = true; // set table initialized
                            table.show(); // display table
                        }
                        fixedColumns();
                        Metronic.initUniform($('input[type="checkbox"]', table)); // reinitialize uniform checkboxes on each table reload
                        Metronic.initUniform($('input[type="checkbox"]', $(optTable))); // reinitialize uniform checkboxes on each table reload
                        countSelectedRecords(); // reset selected records indicator
                        bindCheckboxGroupChange();
                        bindCheckboxChange();
                        bindSubmitClick();
                        bindCancelClick();
						//$("#datatable_playmethodrules").treetable({column:2,expandable: true,initialState:"expanded"}, true);
                    }
                }
            }, options);

            tableOptions = options;

            // create table's jquery object
            table = $(options.src);
            tableContainer = table.parents(".table-container");
            optTable = options.fixedColumns > 0 ? "#fixedTable" : options.src;

            // apply the special class that used to restyle the default datatable
            var tmp = $.fn.dataTableExt.oStdClasses;

            $.fn.dataTableExt.oStdClasses.sWrapper = $.fn.dataTableExt.oStdClasses.sWrapper + " dataTables_extended_wrapper";
            $.fn.dataTableExt.oStdClasses.sFilterInput = "form-control input-small input-sm input-inline";
            $.fn.dataTableExt.oStdClasses.sLengthSelect = "form-control input-xsmall input-sm input-inline";

			//设置查询参数
			applyFilter(true);

            // initialize a datatable
            dataTable = table.DataTable(options.dataTable);

            // revert back to default
            $.fn.dataTableExt.oStdClasses.sWrapper = tmp.sWrapper;
            $.fn.dataTableExt.oStdClasses.sFilterInput = tmp.sFilterInput;
            $.fn.dataTableExt.oStdClasses.sLengthSelect = tmp.sLengthSelect;

            // get table wrapper
            tableWrapper = table.parents('.dataTables_wrapper');

            // build table group actions panel
            if ($('.table-actions-wrapper', tableContainer).size() === 1) {
                $('.table-group-actions', tableWrapper).html($('.table-actions-wrapper', tableContainer).html()); // place the panel inside the wrapper
                $('.table-actions-wrapper', tableContainer).remove(); // remove the template container
            }
			
			// 日期控件
			$('.date-picker').each(function(index, element) {
				var el = $('input', this);
				var fmt = $(this).attr('data-date-format');
				$('input,button', this).click(function(e) {
					WdatePicker({el:el[0], dateFmt:fmt});
				});
			});
			
			// 回车查询
			$('textarea.form-filter, select.form-filter, input.form-filter', table).bind('keypress', function(event){
				if (event.keyCode == '13') {
					submitFilter();
				}
			});
            
        },
        
        getSelectedRowsCount: function () {
            return $(checkbox + ':checked', optTable).size();
        },

        getSelectedRows: function () {
            var rows = [];
            $(checkbox + ':checked', optTable).each(function () {
                rows.push($(this).val());
            });
            return rows;
        },

        setAjaxParam: function (name, value) {
            ajaxParams[name] = value;
        },

        addAjaxParam: function (name, value) {
            if (!ajaxParams[name]) {
                ajaxParams[name] = [];
            }

            skip = false;
            for (var i = 0; i < (ajaxParams[name]).length; i++) { // check for duplicates
                if (ajaxParams[name][i] === value) {
                    skip = true;
                }
            }

            if (skip === false) {
                ajaxParams[name].push(value);
            }
        },

        clearAjaxParams: function (name, value) {
            ajaxParams = {};
        },

        getDataTable: function () {
            return dataTable;
        },

        getTableWrapper: function () {
            return tableWrapper;
        },

        gettableContainer: function () {
            return tableContainer;
        },

        getTable: function () {
            return table;
        }

    };

};

// 实例化表格
var grid = new Datatable();



$(function () {
	
	// 删除操作
	$(document).on('click', '[data-toggle="delete"]', function (e) {
		var $this = $(this);
		var href = $this.attr('href');
		e.preventDefault();
		bootbox.confirm("确定删除吗？", function(result) {
			if (result) {
				Metronic.request({url: href, success: function(res) { grid.getDataTable().ajax.reload(); }});
			}
		});
	});
	
	// 启用停用
	$(document).on('click', '[data-toggle="request"]', function (e) {
		var $this = $(this);
		var href = $this.attr('href');
		e.preventDefault();
		Metronic.request({url: href, success: function(res) { grid.getDataTable().ajax.reload(); }});
	});
	
});